package org.huangrui.spark.java.core.rdd.dep;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.storage.StorageLevel;
import scala.Tuple2;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author hr
 * @Create 2024-10-19 8:29
 */
public class Spark04_Dep_Persist {
    public static void main(String[] args) throws InterruptedException {

        final SparkConf conf = new SparkConf();
        conf.setMaster("local[*]");
        conf.setAppName("spark");

        final JavaSparkContext jsc = new JavaSparkContext(conf);

        final List<Tuple2<String, Integer>> datas = new ArrayList<>();
        datas.add(new Tuple2<String, Integer>("a", 1));
        datas.add(new Tuple2<String, Integer>("a", 2));
        datas.add(new Tuple2<String, Integer>("a", 3));
        datas.add(new Tuple2<String, Integer>("a", 4));

        final JavaRDD<Tuple2<String, Integer>> rdd = jsc.parallelize(datas, 2);
        final JavaPairRDD<String, Integer> mapRdd = rdd.mapToPair(t -> {
            System.out.println("==============================");
            return t;
        });
        // cache默认持久化的操作，只能将数据保存到内存中，如果想要保存到磁盘文件，需要更改存储级别
        mapRdd.cache(); // = mapRdd.persist(StorageLevel.MEMORY_ONLY());
        // 持久化操作必须在行动算子执行时完成的。
        mapRdd.persist(StorageLevel.DISK_ONLY());
        final JavaPairRDD<String, Integer> wordCountRdd = mapRdd.reduceByKey(Integer::sum);
        wordCountRdd.collect();
        System.out.println("计算1完毕");
        System.out.println("*******************************************");

        mapRdd.groupByKey().collect();

        System.out.println("计算2完毕");

        jsc.close();

    }
}
